<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>插件连接测试</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 20px; }
        .status { padding: 10px; margin: 10px 0; border-radius: 5px; }
        .success { background: #d4edda; color: #155724; }
        .error { background: #f8d7da; color: #721c24; }
        .info { background: #d1ecf1; color: #0c5460; }
        button { padding: 10px 20px; margin: 5px; }
        #log { background: #f8f9fa; padding: 15px; border-radius: 5px; height: 300px; overflow-y: auto; font-family: monospace; }
    </style>
</head>
<body>
    <h1>SmartInput 插件连接测试</h1>
    
    <div id="status" class="status info">准备测试...</div>
    
    <button onclick="testConnection()">测试连接</button>
    <button onclick="clearLog()">清除日志</button>
    
    <h3>连接日志：</h3>
    <div id="log"></div>

    <script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
    <script>
        let socket = null;
        const statusDiv = document.getElementById('status');
        const logDiv = document.getElementById('log');
        
        function log(message) {
            const timestamp = new Date().toLocaleTimeString();
            logDiv.innerHTML += `[${timestamp}] ${message}<br>`;
            logDiv.scrollTop = logDiv.scrollHeight;
            console.log(message);
        }
        
        function updateStatus(message, type = 'info') {
            statusDiv.textContent = message;
            statusDiv.className = `status ${type}`;
        }
        
        function clearLog() {
            logDiv.innerHTML = '';
        }
        
        async function testConnection() {
            const urls = [
                'http://localhost:3001',
                'http://127.0.0.1:3001'
            ];

            updateStatus('开始测试连接...', 'info');
            log('开始连接测试');

            for (let i = 0; i < urls.length; i++) {
                const url = urls[i];
                log(`尝试连接到: ${url}`);

                try {
                    // 先测试HTTP连接
                    log(`测试HTTP连接: ${url}/health`);
                    const response = await fetch(`${url}/health`, {
                        method: 'GET',
                        mode: 'cors'
                    });

                    if (response.ok) {
                        const data = await response.json();
                        log(`✅ HTTP连接成功: ${url}`);
                        log(`服务器状态: ${JSON.stringify(data.data)}`);

                        // 测试Socket.io连接
                        await testSocketConnection(url);
                        return;
                    } else {
                        log(`❌ HTTP响应错误: ${response.status} ${response.statusText}`);
                    }
                } catch (error) {
                    log(`❌ HTTP连接失败: ${url} - ${error.message}`);
                    log(`错误详情: ${error.stack}`);
                }
            }

            updateStatus('所有连接尝试都失败了', 'error');
        }
        
        function testSocketConnection(url) {
            return new Promise((resolve, reject) => {
                log(`尝试Socket.io连接: ${url}`);
                
                if (socket) {
                    socket.disconnect();
                }
                
                socket = io(url, {
                    timeout: 5000,
                    reconnection: false
                });
                
                socket.on('connect', () => {
                    log(`✅ Socket.io连接成功: ${url}`);
                    log(`Socket ID: ${socket.id}`);
                    updateStatus(`连接成功: ${url}`, 'success');
                    
                    // 测试设备注册
                    socket.emit('device:register', {
                        type: 'browser',
                        name: 'Test Browser',
                        capabilities: ['text-input']
                    });
                    
                    resolve();
                });
                
                socket.on('connect_error', (error) => {
                    log(`❌ Socket.io连接失败: ${url} - ${error.message}`);
                    reject(error);
                });
                
                socket.on('device:registered', (data) => {
                    log(`✅ 设备注册响应: ${JSON.stringify(data)}`);
                });
                
                socket.on('disconnect', (reason) => {
                    log(`🔌 连接断开: ${reason}`);
                });
            });
        }
        
        // 页面加载时自动测试
        window.addEventListener('load', () => {
            setTimeout(testConnection, 1000);
        });
    </script>
</body>
</html>
